﻿using System.Runtime.CompilerServices;
using DG.Tweening;

namespace LP
{
    using UnityEngine;

    public abstract class UIBase : CancelTokenPattern, IUIBase, IUpdate, ICanUpdate
    {
        //所在Canvas类型
        public EUIType UIType { get; private set; }

        //预制体路径
        public string UIPath { get; private set; }

        //Hide时是否立即销毁   true:缓存不销毁 false:立即销毁该实例和对应的预制体
        public bool IsCache { get; private set; }

        //唯一ID
        public int ID { get; private set; }

        //是否正在显示
        public bool IsShowing { get; private set; }

        //预制体根节点
        public Transform RootTrans { get; private set; }

        //是否可以每帧更新,默认不更新
        public bool IsUpdate { get; set; } = false;

        protected CanvasGroup RootCanvasGroup { get; private set; }

        public UIBase(int id, string uiPath, bool isCache, Transform rootTrans, EUIType uIType)
        {
            ID = id;
            UIPath = uiPath;
            IsCache = isCache;
            RootTrans = rootTrans;
            UIType = uIType;
        }

        public virtual void OnHide(ITuple tuple = null)
        {
            IsShowing = false;
            if (RootTrans != null)
            {
                RootTrans.SetHide();
            }
        }

        public virtual void OnHideBefore()
        {
        }

        public virtual void OnShow(ITuple tuple = null)
        {
            IsShowing = true;
            if (RootTrans != null)
            {
                RootTrans.SetShow();
                RootCanvasGroup.alpha = 0f;
                RootCanvasGroup.DOFade(1f, 0.5f).SetEase(Ease.Linear).SetUpdate(true);
            }
        }

        public virtual void OnShowBefore()
        {
        }

        public override void OnInit()
        {
            base.OnInit();
            RootCanvasGroup = RootTrans.gameObject.AddComponent<CanvasGroup>();
        }

        public override void OnDestroy()
        {
            if (RootTrans != null)
            {
                GameObject.Destroy(RootTrans.gameObject);
            }

            RootTrans = null;
            base.OnDestroy();
        }

        public virtual void OnUpdate(float delta)
        {
        }
    }
}